//
//  HKDisposePoliceViewController.m
//  AQBPolice
//
//  Created by apple on 2017/7/7.
//  Copyright © 2017年 eight. All rights reserved.
//

#import "HKDisposePoliceViewController.h"
#import "RouteAnnotation.h"
#import "JZLocationConverter.h"
#import <BaiduMapAPI_Map/BMKMapComponent.h>
#import <CoreLocation/CoreLocation.h>



@interface HKDisposePoliceViewController ()<UIAlertViewDelegate, UIActionSheetDelegate,BMKMapViewDelegate,BMKLocationServiceDelegate,BMKGeoCodeSearchDelegate,BMKRouteSearchDelegate>
@property (weak, nonatomic) IBOutlet BMKMapView *mapView;

//@property (nonatomic, strong) BMKMapView *mapView;//地图
@property (nonatomic, strong) BMKLocationService *locService;  //定位
@property (nonatomic, strong) BMKGeoCodeSearch *geocodesearch; //地理编码主类，用来查询、返回结果信息

@property (weak, nonatomic) IBOutlet UILabel *addressLabel;
@property (weak, nonatomic) IBOutlet UILabel *poiLabel;
@property (weak, nonatomic) IBOutlet UILabel *distanceLabel;


//路径规划
@property (nonatomic, strong) BMKRouteSearch *routeSearch;

@property (nonatomic, strong) RouteAnnotation* itemStart;
@property (nonatomic, strong) RouteAnnotation* itemEnd;

@end

@implementation HKDisposePoliceViewController

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    
    //获取当前位置
    double currentLongitude = [[NSUserDefaults standardUserDefaults] doubleForKey:@"currentLongitude"];
    double currentLatitude = [[NSUserDefaults standardUserDefaults] doubleForKey:@"currentLatitude"];
    
    //获取目标位置
    double longitude = [[[NSUserDefaults standardUserDefaults] objectForKey:@"longitude"] doubleValue];
    double latitude = [[[NSUserDefaults standardUserDefaults] objectForKey:@"latitude"] doubleValue];
    
    
    HKLog(@"当前的经纬度是%f,%f", currentLongitude, currentLatitude);
    HKLog(@"目的地的经纬度是%f,%f", longitude, latitude);
    
    //开始路径规划(驾车)
    BMKPlanNode *start = [[BMKPlanNode alloc] init];
    start.pt = CLLocationCoordinate2DMake(currentLatitude, currentLongitude);
    
    BMKPlanNode *end = [[BMKPlanNode alloc] init];
    end.pt = CLLocationCoordinate2DMake(latitude, longitude);
    
    BMKWalkingRoutePlanOption *walkingRouteSearchOption = [[BMKWalkingRoutePlanOption alloc]init];
    walkingRouteSearchOption.from = start;
    walkingRouteSearchOption.to = end;
    [self.routeSearch walkingSearch:walkingRouteSearchOption];
    
}


- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.mapView viewWillDisappear];
    self.mapView.delegate = nil; // 不用时，置nil
    self.routeSearch.delegate = nil;
    self.locService.delegate = nil;;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.mapView viewWillAppear];
    //地图代理
    self.mapView.delegate = self;
    //路径规划代理
    self.routeSearch.delegate = self;
    //定位的代理
    self.locService.delegate = self;
    //状态栏黑色
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //在view一加载的时候就初始化路径规划类
    self.routeSearch = [[BMKRouteSearch alloc] init];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(renewUI) name:@"disposePoliceNotification" object:nil];
    
    
    self.mapView.zoomLevel = 15;//地图显示比例
    //创建"完成本次出警"按钮
    UIButton *finishpoliceButton = [[UIButton alloc] init];
    if (kScreen_width == 320) {//5,5s,5SE
        finishpoliceButton = [[UIButton alloc] initWithFrame:CGRectMake(24, kScreen_height-68, 200, 38)];
    }else {
        finishpoliceButton = [[UIButton alloc] initWithFrame:CGRectMake(28, kScreen_height-68, 245, 38)];
    }
    
    finishpoliceButton.backgroundColor = HKColor(253, 151, 39);
    [finishpoliceButton setTitle:@"完成本次出警" forState:UIControlStateNormal];
    finishpoliceButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [finishpoliceButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [finishpoliceButton addTarget:self action:@selector(finishBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:finishpoliceButton];
    
    //创建"导航"按钮
    UIButton *navigationButton = [[UIButton alloc] init];
    if (kScreen_width == 320) {//5,5s,5SE
        navigationButton = [[UIButton alloc] initWithFrame:CGRectMake(240, kScreen_height-68, 62, 38)];
    }else if (kScreen_width == 375){//6,6s,7
        navigationButton = [[UIButton alloc] initWithFrame:CGRectMake(290, kScreen_height-68, 62, 38)];
    }else {//6p,7p
        navigationButton = [[UIButton alloc] initWithFrame:CGRectMake(320, kScreen_height-68, 62, 38)];
    }
    
    [navigationButton setBackgroundImage:[UIImage imageNamed:@"24B90AAC-9C54-421D-906B-889BBB0BCCCD"] forState:UIControlStateNormal];
    [navigationButton setTitle:@"导航" forState:UIControlStateNormal];
    navigationButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [navigationButton setTitleColor:HKColor(253, 151, 39) forState:UIControlStateNormal];
    [navigationButton addTarget:self action:@selector(navBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:navigationButton];
    
    //开始定位方法
    [self startLocation];
}

#pragma mark - actions

- (void)renewUI {
    //获取案件详情
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *address = [userDefaults objectForKey:@"address"];
    if ([address containsString:@"自治区"]) {
        NSString *shortAddress = [address componentsSeparatedByString:@"自治区"][1];
        address = shortAddress;
    }
    NSString *poi = [userDefaults objectForKey:@"poi"];
    double distance = [userDefaults doubleForKey:@"distance"];
    
    self.addressLabel.text = poi;
    self.poiLabel.text = address;
    if (distance > 1000) {
        double currDistance = distance / 1000;
        self.distanceLabel.text = [NSString stringWithFormat:@"%.2lf公里", currDistance];
    }else {
        self.distanceLabel.text = [NSString stringWithFormat:@"%.2lf米", distance];
    }
}

//完成本次出警按钮点击
- (void)finishBtnClicked {
    
    UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"确认已处理" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
    [alert show];
    
    
}

//导航按钮点击事件，跳转到第三方地图界面
- (void)navBtnClicked {
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"选择导航" delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:@"百度地图", @"高德地图", @"取消", nil];
    [sheet showInView:self.view];
}

//打电话按钮点击
- (IBAction)callButtonClicked:(id)sender {
    
    HKLog(@"打电话");
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *string = [userDefaults objectForKey:@"civilianTel"];
    
    HKLog(@"报案人的电话是%@", string);
    NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@",string];
    UIWebView * callWebview = [[UIWebView alloc] init];
    [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
    [self.view addSubview:callWebview];
}

//开始定位
- (void)startLocation{
    
    //初始化BMKLocationService
    self.locService = [[BMKLocationService alloc]init];
    self.locService.delegate = self;
    self.locService.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
    
    _mapView.showsUserLocation = NO;
    _mapView.userTrackingMode = BMKUserTrackingModeFollowWithHeading;
    _mapView.showsUserLocation = YES;
    //启动LocationService
    [self.locService startUserLocationService];
}


//根据polyline设置地图范围
- (void)mapViewFitPolyLine:(BMKPolyline *) polyLine {
    CGFloat ltX, ltY, rbX, rbY;
    if (polyLine.pointCount < 1) {
        return;
    }
    BMKMapPoint pt = polyLine.points[0];
    ltX = pt.x, ltY = pt.y;
    rbX = pt.x, rbY = pt.y;
    for (int i = 1; i < polyLine.pointCount; i++) {
        BMKMapPoint pt = polyLine.points[i];
        if (pt.x < ltX) {
            ltX = pt.x;
        }
        if (pt.x > rbX) {
            rbX = pt.x;
        }
        if (pt.y > ltY) {
            ltY = pt.y;
        }
        if (pt.y < rbY) {
            rbY = pt.y;
        }
    }
    BMKMapRect rect;
    rect.origin = BMKMapPointMake(ltX , ltY);
    rect.size = BMKMapSizeMake(rbX - ltX, rbY - ltY);
    [_mapView setVisibleMapRect:rect];
    _mapView.zoomLevel = _mapView.zoomLevel - 0.3;
}

#pragma mark - UIAlertView delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        //已经处理案件
        [self completeAlarmWithAlarmId:alarmNum andPoliceId:policeNumber];
        //发送通知，显示收工按钮
        [[NSNotificationCenter defaultCenter] postNotificationName:@"goHomeButtonNotification" object:nil];

        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        //获取目标位置
        double longitude = [[[NSUserDefaults standardUserDefaults] objectForKey:@"longitude"] doubleValue];
        double latitude = [[[NSUserDefaults standardUserDefaults] objectForKey:@"latitude"] doubleValue];
        
        HKLog(@"目的地的位置是%f, %f", longitude, latitude);
        
        //跳转到百度地图
        NSString *urlString = [[NSString stringWithFormat:@"baidumap://map/direction?origin={{我的位置}}&destination=latlng:%f,%f|name=目的地&mode=walking&coord_type=bd09ll",latitude, longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
        
        
    }else if (buttonIndex == 1){
//        //获取目标位置
//        double latitude = [[[NSUserDefaults standardUserDefaults] objectForKey:@"latitude"] doubleValue];
//        double longitude = [[[NSUserDefaults standardUserDefaults] objectForKey:@"longitude"] doubleValue];
//        CLLocationCoordinate2D gcj02 = [JZLocationConverter bd09ToGcj02:CLLocationCoordinate2DMake(latitude, longitude)];
//
//        //跳转到高德地图
//        HKLog(@"目的地的位置是%f, %f", longitude, latitude);
//        NSString *scheme = @"AQBScheme://com.cgwx.eightzg.AQBPolice";
//        NSString *appName = @"安全警宝";
//        NSString *urlString = [[NSString stringWithFormat:@"iosamap://navi?sourceApplication=%@&backScheme=%@&lat=%f&lon=%f&dev=0&style=3",appName,scheme, gcj02.latitude, gcj02.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//        
//        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
    }else {
        HKLog(@"取消");
    }
}


#pragma mark - 网络请求
- (void)completeAlarmWithAlarmId:(NSString *)alarmId andPoliceId:(NSString *)policeId {
    NSURLSession *session = [NSURLSession sharedSession];
    NSString *urlString = [baseURL stringByAppendingString:@"mobile/police/completeAlarm/"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    request.HTTPMethod = @"POST";
    NSString *alarmStr = [NSString stringWithFormat:@"alarmId=%@", alarmId];//参数1：案件编号
    NSString *policeStr = [NSString stringWithFormat:@"&policeId=%@", policeId];//参数2：警号
    
    request.HTTPBody = [[alarmStr stringByAppendingString:policeStr] dataUsingEncoding:NSUTF8StringEncoding];
    
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSLog(@"%@",[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
        if (data == nil) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD showError:@"网络错误" toView:self.view];
            });
        }else {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
            if ([dict[@"meta"] isEqual: @"success"]) {
                HKLog(@"已经处理案件");
                //发送通知，通知SecureVC界面收起接警详情界面
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSNotification *notification =[NSNotification notificationWithName:@"didDisposePoliceNotification" object:nil userInfo:nil];
                    [[NSNotificationCenter defaultCenter] postNotification:notification];
                });
            }else {//发送实时位置失败
                HKLog(@"处理案件失败");
            }
        }
    }];
    [task resume];
}

#pragma mark - 百度地图代理方法

#pragma mark - 添加标记物代理方法
- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id<BMKAnnotation>)annotation{
    BMKPinAnnotationView *newAnnotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"myAnnotation"];
    newAnnotationView.pinColor = BMKPinAnnotationColorPurple;
    newAnnotationView.animatesDrop = YES;// 设置该标注点动画显示
    newAnnotationView.annotation=annotation;
    if (annotation == self.itemStart) {
        newAnnotationView.image = [UIImage imageNamed:@"起点"];
    }else if(annotation == self.itemEnd){
        newAnnotationView.image = [UIImage imageNamed:@"终点"];
    }else {
        newAnnotationView.image = nil;
    }
    
    return newAnnotationView;
}

//路径划线代理方法
- (BMKOverlayView*)mapView:(BMKMapView *)map viewForOverlay:(id<BMKOverlay>)overlay
{
    if ([overlay isKindOfClass:[BMKPolyline class]]) {
        BMKPolylineView* polylineView = [[BMKPolylineView alloc] initWithOverlay:overlay];
        polylineView.fillColor = HKColor(253, 151, 39);
        polylineView.strokeColor = HKColor(253, 151, 39);
        polylineView.lineWidth = 3.0;
        return polylineView;
    }
    return nil;
}

#pragma mark - map delegate
//处理位置坐标更新
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation {
    NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    //普通态
    //以下_mapView为BMKMapView对象
    [_mapView updateLocationData:userLocation]; //更新地图上的位置
    _mapView.centerCoordinate = userLocation.location.coordinate; //更新当前位置到地图中间
    //地理反编码
    BMKReverseGeoCodeOption *reverseGeocodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
    reverseGeocodeSearchOption.reverseGeoPoint = userLocation.location.coordinate;
    BOOL flag = [_geocodesearch reverseGeoCode:reverseGeocodeSearchOption];
    if(flag){
        NSLog(@"反geo检索发送成功");
        [_locService stopUserLocationService];
    }else{
        NSLog(@"反geo检索发送失败");
    }
}

#pragma mark - 路径规划代理方法
//走路
- (void)onGetWalkingRouteResult:(BMKRouteSearch*)searcher result:(BMKWalkingRouteResult*)result errorCode:(BMKSearchErrorCode)error
{
    NSLog(@"onGetWalkingRouteResult error:%d", (int)error);
    NSArray* array = [NSArray arrayWithArray:_mapView.annotations];
    [_mapView removeAnnotations:array];
    array = [NSArray arrayWithArray:_mapView.overlays];
    [_mapView removeOverlays:array];
    if (error == BMK_SEARCH_NO_ERROR) {
        BMKWalkingRouteLine* plan = (BMKWalkingRouteLine*)[result.routes objectAtIndex:0];
        NSInteger size = [plan.steps count];
        int planPointCounts = 0;
        for (int i = 0; i < size; i++) {
            BMKWalkingStep* transitStep = [plan.steps objectAtIndex:i];
            if(i==0){
                self.itemStart = [[RouteAnnotation alloc]init];
                self.itemStart.coordinate = plan.starting.location;
                self.itemStart.title = @"起点";
                self.itemStart.type = 0;
                [_mapView addAnnotation:self.itemStart]; // 添加起点标注
                
            }
            if(i==size-1){
                self.itemEnd = [[RouteAnnotation alloc]init];
                self.itemEnd.coordinate = plan.terminal.location;
                self.itemEnd.title = @"终点";
                self.itemEnd.type = 1;
                [_mapView addAnnotation:self.itemEnd]; // 添加终点标注
            }            //添加annotation节点
            RouteAnnotation* item = [[RouteAnnotation alloc]init];
            item.coordinate = transitStep.entrace.location;
            item.title = transitStep.entraceInstruction;
            item.degree = transitStep.direction * 30;
            item.type = 4;
            [_mapView addAnnotation:item];
            
            //轨迹点总数累计
            planPointCounts += transitStep.pointsCount;
        }
        
        //轨迹点
        BMKMapPoint * temppoints = new BMKMapPoint[planPointCounts];
        int i = 0;
        for (int j = 0; j < size; j++) {
            BMKWalkingStep* transitStep = [plan.steps objectAtIndex:j];
            int k=0;
            for(k=0;k<transitStep.pointsCount;k++) {
                temppoints[i].x = transitStep.points[k].x;
                temppoints[i].y = transitStep.points[k].y;
                i++;
            }
            
        }
        // 通过points构建BMKPolyline
        BMKPolyline* polyLine = [BMKPolyline polylineWithPoints:temppoints count:planPointCounts];
        [_mapView addOverlay:polyLine]; // 添加路线overlay
        delete []temppoints;
        [self mapViewFitPolyLine:polyLine];
    } else if (error == BMK_SEARCH_AMBIGUOUS_ROURE_ADDR) {
        
    }
}

- (void)willStartLocatingUser
{
    NSLog(@"start locate");
}

/**
 *用户方向更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
    [_mapView updateLocationData:userLocation];
    NSLog(@"heading is %@",userLocation.heading);
}

@end
